import base64
import time
import sys
from ucloudbiz.server.vm.deployvirtualmachine import deployVirtualMachine
from ucloudbiz.server.vm.listavailableproducttypes import listAvailableProductTypes
from ucloudbiz.server.vm.listvirtualmachines import listVirtualMachines
from ucloudbiz.server.portforwarding.listfirewallrules import listFirewallRules
from ucloudbiz.server.lib.queryAsyncJobResult import queryAsyncJobResult
from ucloudbiz.server.address.listpublicipaddresses import listPublicIpAddresses
from ucloudbiz.server.portforwarding.createportforwardingrule import createPortForwardingRule
from ucloudbiz.server.portforwarding.listportforwardingrules import listPortForwardingRules

import logging
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)s %(message)s')
logger = logging.getLogger('ucloud-hpc')
hdlr = logging.FileHandler('/root/hpc/log/product.log')
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
hdlr.setFormatter(formatter)
logger.addHandler(hdlr)
logger.setLevel(logging.DEBUG)

TIMEOUT=20
offering = None

def createFWD(url, apikey, secret):
    inst = listFirewallRules(url, apikey, secret)
    print "######### Firewall Rules #######"
    print inst.execute()
    
    inst = listPortForwardingRules(url, apikey, secret)
    print "######### Port Forwarding Rules ########"
    print inst.execute()
    
    inst = listPublicIpAddresses(url, apikey, secret)
    p = {}
    print inst.execute(p)
    print "\n\n"
    ipaddressid      = raw_input("     ipaddressid=>")
    virtualmachineid = raw_input("virtualmachineid=>")
    private = raw_input("private port:")
    public  = raw_input("public  port:")
    tcp     = raw_input("TCP/UDP:")

    print "%s(%s)---%s---%s(%s)" % (ipaddressid, public, tcp, virtualmachineid, private)
    yn = raw_input("is it correct(y/n)?")
    if yn.lower() != "y":
        return
    #find ipaddress id
    p = {
        'ipaddressid' : ipaddressid,
        'privateport' : int(private),
        'protocol'    : tcp,
        'publicport'  : int(public),
        'virtualmachineid':virtualmachineid,
        'openfirewall' : 'true',
        }

    if yn.lower() == "y":
        inst = createPortForwardingRule(url,apikey,secret)
        print inst.execute(p)



if __name__ == "__main__":
    from optparse import OptionParser
    usage = "usage: %prog [options] arg"
    parser = OptionParser()
    
    parser.add_option("-a","--apikey", dest="apikey",help="API Key")
    parser.add_option("-s","--secret", dest="secret",help="Secret Key")
    parser.add_option("-u","--url", dest="url",help="API Server URL")
    
    (options,args) = parser.parse_args()

    if not options.apikey:
        apikey = raw_input("APIKEY=>")
        
    else:
        apikey = options.apikey	

    if not options.secret:
        secret = raw_input("SECRET=>")
    else:
        secret = options.secret

    if not options.url:
        #ucloud openapi
        url = "https://api.ucloudbiz.olleh.com/server/v1/client/api?"
       
    else:
        url = options.url

    logger.debug("############## Start to ucloud cli #############")
    logger.debug("APIKEY:%s" % apikey)
    logger.debug("SECRET:%s" % secret)

    print "\n\n\n\n"
    print "########### Warning ###########################"
    print "API URL : %s" % url
    print "###############################################"
    print "\n\n"
    yn = raw_input("URL is corrent(y/n)")
    if yn.lower() != "y":
        print "Exiting...."
        sys.exit()

    print createFWD(url, apikey, secret)
       
    sys.exit()

   

